package com.example.day18_19;

import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    final int CANT_PLAY=0;
    final int CAN_PLAY=1;
    final int PLAYING=2;
    final int PAUSE=3;
    final int CHANGE=4;
    TextView text1;
    Button bendi;
    SeekBar progress;

    ListView music_list;//播放列表
    List<musicData> datalist = null;
    musicAdapter adapter;
    musicData nowMusic;
    MediaPlayer mp;
    Button play, stop, next, last;
    int isCanStart = CANT_PLAY;//播放状态0：未准备完成 1准备完成 2播放中 3暂停 4换曲

    //    boolean hadDestroy=false;
    int playTime = 0;

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 100:
                    Log.e("#####", "handler" + playTime);
                    progress.setProgress(playTime);
                    break;
                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mp = new MediaPlayer();
        text1 = findViewById(R.id.name);
        music_list = findViewById(R.id.list1);
        progress = findViewById(R.id.progress);
        play = findViewById(R.id.play);
        stop = findViewById(R.id.stop);
        next = findViewById(R.id.next);
        last = findViewById(R.id.last);
        play.setOnClickListener(this);
        stop.setOnClickListener(this);
        next.setOnClickListener(this);
        last.setOnClickListener(this);
        bendi = findViewById(R.id.bendi);
        bendi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkAccess("android.permission.WRITE_EXTERNAL_STORAGE", 1);
            }
        });
        music_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                nowMusic=datalist.get(position);
                musicStop();
                isCanStart=CHANGE;
                initPlayer(nowMusic);
            }
        });
        progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int aa=0;
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                Log.i("######","onProgressChanged=" +progress);
                aa=progress;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                Log.i("######","onStartTrackingTouch=");
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                Log.i("######","onStopTrackingTouch=");
                playTime=aa; 
                mp.seekTo(playTime);
            }
        });

        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                Log.e("####","播放完毕");
                musicStop();
                isCanStart=CHANGE;
                int num2 = nowMusic.getSort();
                if (num2 == datalist.size() - 1) {
                    num2 = 0;
                } else {
                    num2 = num2 + 1;
                }
                nowMusic = datalist.get(num2);
                initPlayer(nowMusic);
            }
        });


    }


    private void checkAccess(String access, int code) {
        //Manifest.permission.READ_EXTERNAL_STORAGE
        //检查当前权限（若没有该权限，值为-1；若有该权限，值为0）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int hasAccess = ContextCompat.checkSelfPermission(getApplication(), access);
            Log.e("PERMISION_CODE", hasAccess + "***");
            if (hasAccess == PackageManager.PERMISSION_GRANTED) {
                // TODO: 2019/6/15 获得授权执行操作
                music();

            } else {
                ActivityCompat.requestPermissions(this, new String[]{access, "android.permission.READ_EXTERNAL_STORAGE"}, code);
            }
        } else {
            // TODO: 2019/6/15 非6.0直接使用
            Log.e("PERMISION_CODE", "非6.0***");
            music();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        android.permission.WRITE_EXTERNAL_STORAGE
        if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // TODO: 2019/6/15 获得授权执行操作
//http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&page=1
            music();
        } else {
            // TODO: 2019/6/15 未获得授权执行的操作
            finish();
        }
    }


    public void music() {
        //TODO 1:获得ContentResolver
        ContentResolver contentResolver = getContentResolver();
        //参数一 URI   null
        //TODO 2:获得音频的URI
        Uri uri1 = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;//音频的URI
        Log.e("PERMISION_CODE", uri1.getPath() + "***");
        Cursor cursor = contentResolver.query(uri1, null, null, null, null);
        Log.e("111######", cursor.getCount() + "没有音乐！！！");
        if (cursor == null || cursor.getCount() <= 0) {
            Log.e("######", "没有音乐！！！");
            return;
        }
        datalist = new ArrayList<>();
        int a = 0;
        while (cursor.moveToNext()) {
            //字段
            musicData mdata = new musicData();
            String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
            long size = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE));

            mdata.setTitle(title);
            mdata.setArtist(artist);
            mdata.setData(data);
            mdata.setDuration(duration);
            mdata.setSize(size);
            mdata.setSort(a);
            a++;
            datalist.add(mdata);

            Log.e("###", "音乐: " + title + ":" + data + ":" + artist + ":" + duration + ":" + size);
        }
        adapter = new musicAdapter(MainActivity.this, datalist);
        music_list.setAdapter(adapter);
        nowMusic = datalist.get(0);
        initPlayer(nowMusic);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play:
                if (isCanStart==CANT_PLAY) {
                    Toast.makeText(MainActivity.this, "音频文件未准备好", Toast.LENGTH_SHORT).show();
                    break;
                }
                if (!mp.isPlaying()) {
                    musicPlay();
                } else {
                    isCanStart=PAUSE;
                    mp.pause();
                }
                break;

            case R.id.stop:
                if (mp.isPlaying()||isCanStart==CANT_PLAY) {
                   musicStop();
                    initPlayer(nowMusic);
                }
                break;
            case R.id.last:
                if (isCanStart==CANT_PLAY) {
                    Toast.makeText(MainActivity.this, "音频文件未准备好", Toast.LENGTH_SHORT).show();
                    break;
                }
                musicStop();
                isCanStart=CHANGE;
                int num = nowMusic.getSort();
                if (num == 0) {
                    num = datalist.size() - 1;
                } else {
                    num = num - 1;
                }
                nowMusic = datalist.get(num);
                initPlayer(nowMusic);
                break;
            case R.id.next:
                if (isCanStart==CANT_PLAY) {
                    Toast.makeText(MainActivity.this, "音频文件未准备好", Toast.LENGTH_SHORT).show();
                    break;
                }
                musicStop();
                isCanStart=CHANGE;
                int num2 = nowMusic.getSort();
                if (num2 == datalist.size() - 1) {
                    num2 = 0;
                } else {
                    num2 = num2 + 1;
                }
                nowMusic = datalist.get(num2);
                initPlayer(nowMusic);
                break;
            default:
                break;
        }
    }

    private void musicPlay() {
        isCanStart=PLAYING;
        mp.seekTo(playTime);
        mp.start();
        int totalTime = Math.round(mp.getDuration() / 1000);
        String str = String.format("%02d:%02d", totalTime / 60,
                totalTime % 60);
        text1.setText(nowMusic.getTitle()+str);
        progress.setMax(mp.getDuration());
        new myThread().start();
    }
    private void musicStop() {
        isCanStart=CANT_PLAY;
        mp.stop();
        mp.reset();
        playTime=0;
        progress.setProgress(0);
    }

    private class myThread extends Thread {

        @Override
        public void run() {
            Log.e("#########", mp.isPlaying() + "播放");

            while (mp.isPlaying()) {

                playTime = mp.getCurrentPosition();
                Log.e("#########", playTime + "");
                mHandler.sendEmptyMessage(100);
                if (playTime >= mp.getDuration()) {
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
            }
        }
    }

    private boolean initPlayer(musicData data) {
        Log.e("#####",data.getTitle()+"");
        if(isCanStart!=CHANGE){
            isCanStart = CANT_PLAY;
        }
        String filename = data.getData();
        File file = new File(filename);
        try {
            mp.setDataSource(file.getPath());
            Log.e("播放器", file.toString());
            mp.prepareAsync();
            mp.setOnPreparedListener(new mpListener());
            text1.setText(nowMusic.getTitle());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private class mpListener implements MediaPlayer.OnPreparedListener {

        @Override
        public void onPrepared(MediaPlayer mp) {
            if(isCanStart==CHANGE){
                musicPlay();
            }else {
                isCanStart = CAN_PLAY;
            }
//            if(isCanStart==CAN_PLAY){
//
//            }
        }
    }

    @Override
    protected void onDestroy() {
        // TODO 自动生成的方法存根
        super.onDestroy();
        if (mp != null) {
            mp.stop();
            mp.release();
        }
    }
}
